package www.openteam.com.ui.qualityCntrl;


import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import www.openteam.com.R;
import www.openteam.com.base.mBaseFragment;
import www.openteam.com.bean.IQCCheckItem;
import www.openteam.com.bean.IQCDefectdItem;
import www.openteam.com.bean.IQCMsg00;
import www.openteam.com.contract.qualityCntrl.IQC00Contract;
import www.openteam.com.presenter.qualityCntrl.IQC00Presenter;
import www.openteam.com.tool.ToastUtil;

/**
 * A simple {@link Fragment} subclass.
 */
public class IQC00Fragment extends mBaseFragment<IQC00Presenter>
        implements IQC00Contract.IQC00View {

    IQCMsg00.DataBeanX.DataBean data00;
    @Bind(R.id.iqc00_date)
    TextView iqc00Date;
    @Bind(R.id.iqc00_purchaseNo)
    TextView iqc00PurchaseNo;
    @Bind(R.id.iqc00_stockNo)
    TextView iqc00StockNo;
    @Bind(R.id.iqc00_batchNo)
    TextView iqc00BatchNo;
    @Bind(R.id.iqc00_code)
    TextView iqc00Code;
    @Bind(R.id.iqc00_name)
    TextView iqc00Name;
    @Bind(R.id.iqc00_specs)
    TextView iqc00Specs;
    @Bind(R.id.iqc00_unit)
    TextView iqc00Unit;
    @Bind(R.id.iqc00_pNum)
    TextView iqc00PNum;
    @Bind(R.id.iqc00_cNum)
    TextView iqc00CNum;
    @Bind(R.id.iqc00_BasisWeight)
    EditText iqc00BasisWeight;
    @Bind(R.id.iqc00_SpotCheck)
    EditText iqc00SpotCheck;
    @Bind(R.id.iqc00_BadNum)
    TextView iqc00BadNum;
    @Bind(R.id.iqc00_RejectRatio)
    TextView iqc00RejectRatio;
    @Bind(R.id.iqc_NAddView)
    ImageButton addBtn;
    @Bind(R.id.iqc_RemoveView)
    ImageButton removeBtn;
    @Bind(R.id.iqc_childItem)
    LinearLayout mChildLinearLayout;
    @Bind(R.id.iqc00_Decide)
    Spinner iqc00Decide;
    @Bind(R.id.iqc00_MBA)
    Spinner iqc00MBA;
    @Bind(R.id.iqc00_ReciverNum)
    EditText iqc00ReciverNum;
    @Bind(R.id.iqc00_ReturnNum)
    EditText iqc00ReturnNum;
    @Bind(R.id.iqc_save)
    Button btn_save;
    @Bind(R.id.iqc_cancle)
    Button btn_cancle;
    @Bind(R.id.iqc_audit)
    Button btn_audit;
    @Bind(R.id.iqc_Unaudit)
    Button btn_unAudit;

    private List<IQCCheckItem.DataBeanX.DataBean> checkItemData;
    private ArrayAdapter<String> checkItemAdapter;
    private ArrayAdapter<String> badItemAdapter;
    private String TAG = getClass().getSimpleName();
    private ArrayList<ViewHolder> viewHolderList;
    private ArrayList<View> viewList;
    private View mChildView;
    int markId = 0;
    private List<IQCDefectdItem.DataBeanX.DataBean> defectData;
    private int tag = 0;
    private ArrayList<ArrayAdapter<String>> arrayAdapters;


    public IQC00Fragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_iqc00, container, false);
        ButterKnife.bind(this, view);
        mPresenter = loadPresenter();
        initData();
        initView();
        initListener();
        return view;
    }

    /**
     * 采购IQC
     */
    public void getData00(IQCMsg00.DataBeanX.DataBean dataBean) {
        data00 = dataBean;
    }

    /**
     * 外发退料IQC
     */
    public void getData01() {

    }

    @Override
    protected void initData() {
        if (mPresenter != null)
            mPresenter.attachView(this);

        ArrayList<String> decideList = new ArrayList<>();
        decideList.add("接收");
        decideList.add("拒收");
        ArrayAdapter<String> decideAdapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, decideList);
        decideAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        iqc00Decide.setAdapter(decideAdapter);

        ArrayList<String> MBAList = new ArrayList<>();
        MBAList.add("特采");
        MBAList.add("选用");
        MBAList.add("退货");
        ArrayAdapter<String> MBAAdapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, MBAList);
        MBAAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        iqc00MBA.setAdapter(MBAAdapter);

        arrayAdapters = new ArrayList<>();

        if (null != data00) {
            iqc00Date.setText(data00.getEnterdate());
            iqc00PurchaseNo.setText(data00.getPurchNo());
            iqc00StockNo.setText(data00.getRdsno());
            iqc00BatchNo.setText(data00.getBatchNo());
            iqc00Code.setText(data00.getMaterialCode());
            iqc00Name.setText(data00.getMaterialName());
            iqc00Specs.setText(data00.getSpecs());
            iqc00Unit.setText(data00.getUnit());
            iqc00PNum.setText(data00.getPurchNumb());
            iqc00CNum.setText(data00.getBnumber());
        }

        mPresenter.findCheckItem();
    }

    @Override
    protected void initListener() {
        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                markId++;
                mChildView = View.inflate(getContext(), R.layout.iqc_child_layout, null);
                mChildView.setId(markId);
                getViewInstance(mChildView);
                mChildLinearLayout.addView(mChildView);
            }
        });
        removeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int childNum = mChildLinearLayout.getChildCount();
                if (childNum > 1) {
                    mChildLinearLayout.removeViewAt(childNum - 1);
                    viewHolderList.remove(viewHolderList.size() - 1);
                    viewList.remove(viewList.size() - 1);
                    markId--;
                }
            }
        });

        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!iqc00ReciverNum.getText().toString().isEmpty() &&
                        !iqc00ReturnNum.getText().toString().isEmpty()) {
                    int reciverNum = Integer.valueOf(iqc00ReciverNum.getText().toString());
                    int returnNum = Integer.valueOf(iqc00ReturnNum.getText().toString());
                    try {
                        double purchNumb = Double.valueOf(data00.getPurchNumb());
                        Log.e(TAG, "onClick: "+purchNumb );
                        if (reciverNum + returnNum == purchNumb) {
                            int childId = data00.getId();
                            String rdson = data00.getRdsno();
                            btn_audit.setVisibility(View.VISIBLE);
                            btn_unAudit.setVisibility(View.VISIBLE);
                            ToastUtil.showToast(getContext(), "保存成功");
                        } else {
                            ToastUtil.showToast(getContext(), "接受数加上退货数应等于入库数量");
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.showToast(getContext(), "请输入接受数和退货数");
                }

            }
        });

        btn_audit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AlertDialog.Builder(getContext())
                        .setTitle("提示")
                        .setMessage("记录审核后不能进行修改和删除，是否确认审核")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                iqc00BasisWeight.setEnabled(false);
                                iqc00SpotCheck.setEnabled(false);
                                iqc00ReciverNum.setEnabled(false);
                                iqc00ReturnNum.setEnabled(false);
                                iqc00Decide.setEnabled(false);
                                iqc00MBA.setClickable(false);
                                addBtn.setClickable(false);
                                removeBtn.setClickable(false);
                            }
                        })
                        .setNegativeButton("否", null)
                        .show();
            }
        });
        btn_unAudit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AlertDialog.Builder(getContext())
                        .setTitle("提示")
                        .setMessage("是否进行反审核")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                iqc00BasisWeight.setEnabled(true);
                                iqc00SpotCheck.setEnabled(true);
                                iqc00ReciverNum.setEnabled(true);
                                iqc00ReturnNum.setEnabled(true);
                                iqc00Decide.setEnabled(true);
                                iqc00MBA.setClickable(true);
                                addBtn.setClickable(true);
                                removeBtn.setClickable(true);
                            }
                        })
                        .setNegativeButton("否", null)
                        .show();
            }
        });
    }

    @Override
    protected void initView() {
        viewHolderList = new ArrayList<>();
        viewList = new ArrayList<>();
//        mChildView = View.inflate(getContext(), R.layout.iqc_child_layout, null);
//        mChildView.setId(markId);
//        getViewInstance(mChildView);
//        mChildLinearLayout.addView(mChildView);
        //首先隐藏审核和反审核按钮
        btn_audit.setVisibility(View.INVISIBLE);
        btn_unAudit.setVisibility(View.INVISIBLE);
    }

    private void getViewInstance(View mChildView) {
        ViewHolder vh = new ViewHolder();
        vh.id = mChildView.getId();
        vh.CcheckItem = (Spinner) mChildView.findViewById(R.id.iqc_CheckItem);
        vh.CbadItem = (Spinner) mChildView.findViewById(R.id.iqc_BadItem);
        vh.Cnum = (EditText) mChildView.findViewById(R.id.iqc_BadNum);
        //设置数据
        vh.CcheckItem.setAdapter(checkItemAdapter);

        // 设置监听

        vh.CcheckItem.setOnItemSelectedListener(checkItemListener);
        vh.CbadItem.setOnItemSelectedListener(badItemListener);
        viewHolderList.add(vh);
        viewList.add(mChildView);
    }

    private ViewHolder viewHolderNow;
    AdapterView.OnItemSelectedListener checkItemListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            IQCCheckItem.DataBeanX.DataBean dataBean = checkItemData.get(i);
            View v2 = (View) adapterView.getParent().getParent();
            for (int j = 0; j < mChildLinearLayout.getChildCount() - 1; j++) {
                ViewHolder viewHolder = viewHolderList.get(j);
                Log.e(TAG, "v2.getId()==" + v2.getId() + "  viewHolder.id==" + viewHolder.id);
                if (v2.getId() == viewHolder.id) {
                    viewHolderNow = viewHolder;
                    mPresenter.findDefectdItem(dataBean.getItemID());
                }
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    };

    AdapterView.OnItemSelectedListener badItemListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    };

    @Override
    protected void otherViewClick(View view) {

    }

    @Override
    protected IQC00Presenter loadPresenter() {
        return new IQC00Presenter();
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void findCheckItem(IQCCheckItem iqcCheckItem) {
        checkItemData = iqcCheckItem.getData().getData();
        ArrayList<String> checkItemList = new ArrayList<>();
        for (IQCCheckItem.DataBeanX.DataBean dataBean : checkItemData) {
            checkItemList.add(dataBean.getItemName());
        }
        checkItemAdapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, checkItemList);
        checkItemAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mChildView = View.inflate(getContext(), R.layout.iqc_child_layout, null);
        mChildView.setId(markId);
        getViewInstance(mChildView);
        mChildLinearLayout.addView(mChildView);
    }

    @Override
    public void findDefectdItem(IQCDefectdItem iqcDefectdItem) {
        tag = 1;
        defectData = iqcDefectdItem.getData().getData();
        ArrayList<String> defectList = new ArrayList<>();
        for (IQCDefectdItem.DataBeanX.DataBean dataBean : defectData) {
            defectList.add(dataBean.getName());
        }
        badItemAdapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, defectList);
        badItemAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        Log.e(TAG, "findDefectdItem: viewHolderNow: " + viewHolderNow.id);
        arrayAdapters.add(badItemAdapter);
        viewHolderNow.CbadItem.setAdapter(badItemAdapter);

    }

    @Override
    public void fail(String msg) {
        Log.e(TAG, "fail: " + msg);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public class ViewHolder {
        private int id = -1;
        private Spinner CcheckItem;
        private Spinner CbadItem;
        private EditText Cnum;
    }
}
